# http://www.apabi.com/ruc/?pid=refbook.index&cult=CN

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import json
from urllib.parse import urlencode
import urllib

proxies = {
        "http": "http://qf:qf3.1415@202.112.118.7:10086/"
    }

def updateCookie(cookies,tempCookies):

    for k, v in tempCookies.items():
        cookies[k] = v

    return cookies

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    lis = soup.select(".search_list_content")

    for li in lis:

        tempData = resultData()

        try:
            tempData["titleName"] = li.select(".title")[0].text.strip()
        except:
            pass

        try:
            tempData["titleHref"] = "http://www.apabi.com" + li.select(".title")[0]["href"]
        except:
            pass

        try:
            tempData["abstract"] = li.select(".comment")[0].text.strip()
        except:
            pass

        allData.append(tempData)

    return allData

def getData(keyword,cookies):


    headers = {
        'Proxy-Connection': 'keep-alive',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://www.apabi.com/ruc/?pid=hybrid.search&wd=%E8%AF%97&cult=CN&hdc=1&orgid=ruc&username=%E6%9D%A5%E8%87%AA%20%E4%B8%AD%E5%9B%BD%E4%BA%BA%E6%B0%91%E5%A4%A7%E5%AD%A6%E5%9B%BE%E4%B9%A6%E9%A6%86%20%E7%9A%84%E7%94%A8%E6%88%B7&ug=%E4%B8%AD%E5%9B%BD%E4%BA%BA%E6%B0%91%E5%A4%A7%E5%AD%A6%E5%9B%BE%E4%B9%A6%E9%A6%86%E6%97%A0%E5%AF%86%E7%A0%81%E7%94%A8%E6%88%B7%E7%BB%84',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('wd', keyword),
        ('cult', 'CN'),
        ('hdc', '1'),
        ('orgid', 'ruc'),
        ('username', '\u6765\u81EA \u4E2D\u56FD\u4EBA\u6C11\u5927\u5B66\u56FE\u4E66\u9986 \u7684\u7528\u6237'),
        ('ug', '\u4E2D\u56FD\u4EBA\u6C11\u5927\u5B66\u56FE\u4E66\u9986\u65E0\u5BC6\u7801\u7528\u6237\u7EC4'),
        ('pid', 'hybrid.search.old'),
    )

    response = requests.get('http://www.apabi.com/ruc/', headers=headers, params=params, cookies=cookies,proxies = proxies)

    allData = formData(response)

    return allData

def getCookies(cookies):

    headers = {
        'Host': 'www.apabi.com',
        'Accept': '*/*',
        'X-Requested-With': 'XMLHttpRequest',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Referer': 'http://www.apabi.com/ruc/pub.mvc/Index2?pid=login&cult=CN',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('pid', 'userinfo'),
        ('cult', 'CN'),
        ('_', '1550886920881'),
    )

    s = requests.session()

    response = s.get('http://www.apabi.com/ruc/pub.mvc/Index2', headers=headers, params=params, cookies=cookies,proxies = proxies)

    print()

    cookies = s.cookies.get_dict()

    return cookies

def login():
    headers = {
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        # 'Referer': 'http://www.apabi.com/ruc/pub.mvc/Index2?pid=login&cult=CN',
    }

    s = requests.session()

    s.get('http://www.apabi.com/ruc/pub.mvc/Index2?pid=login&cult=CN', headers=headers,  proxies=proxies)

    cookies = s.cookies.get_dict()

    return cookies

def login1(cookies):


    headers = {
        'Host': 'www.apabi.com',
        'Cache-Control': 'max-age=0',
        'Origin': 'http://www.apabi.com',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://www.apabi.com/ruc/pub.mvc/Index2?pid=login&cult=CN',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('pid', 'login'),
        ('cult', 'CN'),
    )

    data = {
        'orgid': 'ruc',
        'action': 'login',
        'txtLoginUserType': '',
        'ForcedLogin': '',
        'returl': '',
        'username': '',
        'pwd': '',
        'code': '',
        'txtSystem': '',
        'txtTrueName': '',
        'txtEmail': '',
        'txtTel': '',
        'LoginType': 'IPAutoLogin',
        'chkIsUseImgCode': 'on'
    }
    s = requests.session()
    response = s.post('http://www.apabi.com/ruc/pub.mvc/Index2', headers=headers, params=params, cookies=cookies,
                             data=data,proxies = proxies)
    cookies = s.cookies.get_dict()

    return cookies

def getCookies1(cookies):


    headers = {
        'Host': 'www.apabi.com',
        'Accept': '*/*',
        'X-Requested-With': 'XMLHttpRequest',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Referer': 'http://www.apabi.com/ruc/pub.mvc/Index2?pid=login&cult=CN',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('pid', 'userinfo'),
        ('cult', 'CN'),
        ('_', '1550886921653'),
    )
    s = requests.session()
    response = s.get('http://www.apabi.com/ruc/pub.mvc/Index2', headers=headers, params=params, cookies=cookies)


    cookies = s.cookies.get_dict()

    return cookies


def getIndex(cookies):

    headers = {
        'Proxy-Connection': 'keep-alive',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://www.apabi.com/ruc/?pid=picture.index&cult=CN',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('pid', 'usp.search'),
        ('wd', '\u4E66'),
        ('cult', 'CN'),
        ('ct', ''),
        ('db', 'picture'),
        ('dt', 'Image'),
        ('url', 'picture.index'),
        ('f_type', ''),
    )

    response = requests.get('http://www.apabi.com/ruc/', headers=headers, params=params, cookies=cookies,proxies = proxies)



def index(request):


    # page = 1
    # data = {"values": ["cell"], "type": ["TI"], "log": [""]}
    data = json.loads(request.POST.get('data', '1'))
    cookies = login()
    cookiesT = getCookies(cookies)
    cookies = updateCookie(cookies,cookiesT)

    cookiesT = login1(cookies)
    cookies = updateCookie(cookies, cookiesT)

    cookiesT = getCookies1(cookies)
    cookies = updateCookie(cookies, cookiesT)

    # getIndex(cookies)

    allData = getData(data["values"][0],cookies)

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")